package com.topcheer.provider.rbac.service;

import java.util.List;
import java.util.ArrayList;

import com.topcheer.provider.rbac.entity.Menu;
import com.topcheer.provider.rbac.mapper.MenuMapper;
import org.springframework.stereotype.Service;
import com.topcheer.common.base.service.impl.BaseBiz;

@Service("menuService")
public class MenuService extends BaseBiz<MenuMapper, Menu>{


    public List<Menu> selectMenuByRole(List<Long> list){
        List<Menu> menus = mapper.selectMenuByRole(list);
        return treeMenu(menus);
    }

    public List<Menu> treeMenu(List<Menu> menus){
        List<Menu> result = new ArrayList<>();
        for(Menu menu:menus){
            if(menu.getParentId() == 0l){ //根节点
                List<Menu> menuList = iterator(menus, menu.getId());
                menu.setChildren(menuList);
                result.add(menu);
            }
        }
        return result;
    }

    private List<Menu> iterator(List<Menu> menus, Long id) {
        List<Menu> result = new ArrayList<>();
        for(Menu menu:menus){
            Long parentId = menu.getParentId();
            if(parentId !=0l && parentId == id){
                List<Menu> iterator = iterator(menus, menu.getId());
                menu.setChildren(iterator);
                result.add(menu);
            }
        }
        return result;
    }

    /*public static void main(String[] args) {
        List<Menu> menuList = new ArrayList<>();
        Menu menu = new Menu();
        menu.setId(1l);
        menu.setMenuName("系统管理");
        Menu menu1 = new Menu();
        menu1.setId(2l);
        menu1.setMenuName("菜单管理");
        menuList.add(menu);
        menuList.add(menu1);
        treeMenu(menuList);
    }*/

}
